package com.chen.controller;

import cn.hutool.core.util.StrUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.commons.Result;
import com.chen.entity.*;
import com.chen.mapper.PermissionMapper;
import com.chen.mapper.RoleMapper;
import com.chen.mapper.UserMapper;
import com.chen.utils.MD5Utils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


@RestController
@RequestMapping("/users")
@SuppressWarnings("all")
public class UserController {


    //依赖注入
    @Resource
    UserMapper userMapper;

    @Resource
    RoleMapper roleMapper;

    @Resource
    PermissionMapper permissionMapper;

    public UserController() throws NoSuchAlgorithmException {
    }

    //注册
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error("-2", "用户名重复");
    }
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();


    }

    //登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) throws NoSuchAlgorithmException {
        /*MessageDigest md = MessageDigest.getInstance("MD5");
        String resultString = MD5Utils.stringToMD5(user.getPassword());
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));*/
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("password",user.getPassword());
        queryWrapper.eq("role",user.getRole());
        User res = userMapper.selectOne(queryWrapper);

        if (res == null) {
            return Result.error("-1", "用户名或密码错误");
        }

        HashSet<Permission> permissionSet = new HashSet<>();
        //从user_role中通过用户id查询所有的角色信息
        int userId = res.getId();
        List<UserRole> userRoles = roleMapper.getByUserRoleUserId(userId);
        List<Permission> permissions=new ArrayList<>();

        for (UserRole userRole : userRoles) {
            //.根据roleId从role_permission表查询出所有的permissionId
            List<RolePermisson> rolePermissions = permissionMapper.getRolePermissionByRoleId(userRole.getRoleId());
            for (RolePermisson rolePermission : rolePermissions) {
                int permissionId = rolePermission.getPermissionId();
                //根据permissionId查询permission信息
                Permission permission = permissionMapper.selectById(permissionId);
                permissionSet.add(permission);
            }
        }



        res.setPermissions(permissionSet);
        // 登录成功后 初始化用户信息模板
        UserInfo userInfo = new UserInfo(res);

        return Result.success(userInfo);
        //return Result.success(user);

    }

    //    新增
    @PostMapping
    public Result<?> save(@RequestBody User user) {
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();

    }

    //更新
    @PutMapping
    public Result<?> update(@RequestBody User user) {
        userMapper.updateById(user);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id){
return Result.success(userMapper.selectById(id));
    }
    //删除
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }

    //    查询
//    @GetMapping
//    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,  //页号
//                              @RequestParam(defaultValue = "10") Integer pageSize, //一页展示的数量
//                              @RequestParam(defaultValue = "") String search) {
//
////        模糊查询
//        LambdaQueryWrapper<User> warapper = Wrappers.<User>lambdaQuery().like(User::getNick, search);
//        if (StrUtil.isBlank(search)) {
//            warapper.like(User::getNick, search);
//        }
//        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), warapper);
//        return Result.success(userPage);
//
//    }
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().like(User::getNick, search);
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(User::getNick, search);
        }
        Page<User> userPage = userMapper.findPage(new Page<>(pageNum, pageSize),search);
        return Result.success(userPage);
    }

}
